package com.woniuxy.order.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.order.client.HouseService;

import com.woniuxy.order.entity.JsonResponse;
import com.woniuxy.order.entity.RenthouseOrder;
import com.woniuxy.order.entity.ResponseResult;
import com.woniuxy.order.exception.BusinessException;
import com.woniuxy.order.service.RenthouseOrderService;
import com.woniuxy.order.util.OrderNumberCreator;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author maotao
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/order/renthouseOrder")
public class RenthouseOrderController {
    private static Logger LOG = LoggerFactory.getLogger(RenthouseOrderController.class);

    @Resource
    RenthouseOrderService renthouseOrderService;

    @Resource
    HouseService rentHouseService;

    @Resource
    AmqpTemplate amqpTemplate;

    @ApiResponse(message = "增加订单接口", code = 301)
    @PostMapping("add")
    public ResponseResult add(@Valid RenthouseOrder order) {
        order.setTime(LocalDateTime.now());
        order.setOrderno(OrderNumberCreator.createServerOrderNum());
        amqpTemplate.convertAndSend("topicExchange", "topic.rent", order);
        return ResponseResult.SUCCESS;
    }

    @GetMapping("/findByPage/{currentPage}/{size}")
    @SentinelResource(value = "findByPage",blockHandler = "sentinelTestHandler",fallback = "findByPageTestFallBack")
    public ResponseResult findByPage(@PathVariable("currentPage") Integer currentPage, @PathVariable("size") Integer size) {
        Page<RenthouseOrder> pageResult = renthouseOrderService.page(new Page<>(currentPage, size));
        ResponseResult responseResult = new ResponseResult<>();
        responseResult.setData(pageResult);
        return responseResult;
    }

    @GetMapping("findById/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        RenthouseOrder renthouseOrder = renthouseOrderService.getById(id);
        Integer houseid = renthouseOrder.getHouseid();
        ResponseResult result = rentHouseService.findRentHouseById(id);
        return result;
    }

    @SentinelResource(value = "st", blockHandler = "sentinelTestHandler", fallback = "sentinelTestFallback")
    @GetMapping("/sentinelTest")
    public String sentinelTest(String a) {
        return "sentinelTest方法";
    }

    /**
     * 流控方法：用于sentinelTest方法被流控时触发
     * @param a
     * @param b
     * @param blockException
     * @return
     */
    public String sentinelTestHandler(String a, String b, BlockException blockException) {
        return "---------" + blockException;
    }

    /**
     * 回调方法：用于sentinelTest触发其他异常时的降级方法
     * @param a
     * @param b
     * @param throwable
     * @return
     */
    public String sentinelTestFallback(String a, String b, Throwable throwable) {

        return "---------" + throwable;
    }

    @GetMapping("/sentinelTest2")
    public String sentinelTest2() {

        return renthouseOrderService.test();
    }

    @GetMapping("/addRule")
    public String test() {
//        ArrayList<FlowRule> rules = new ArrayList<>();
//        FlowRule rule = new FlowRule();
//        rule.setRefResource("/order/renthouseOrder/sentinelTest");
//        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        rule.setCount(1);
//        rules.add(rule);
//        FlowRuleManager.loadRules(rules);
        return "ok";
    }


    @PostMapping("create")
    public JsonResponse createOrder(@Valid RenthouseOrder order) {

        LOG.info("order creating , param={}", JSON.toJSON(order));
        if (true) {
            LOG.info("抛出运行时异常");
            throw new BusinessException();
//            return JsonResponse.success(1000L).setMsg("订单创建成功");

        }

        return JsonResponse.serverError().setMsg("创建订单失败");


    }


}